﻿using AgencyManagerSystem.Common;
using AgencyManagerSystem.DataFetcher;
using AgencyManagerSystem.DataUpdater;
using AgencyManagerSystem.Model;
using AgencyManagerSystem.AsmType;
using System;

namespace AgencyManagerSystem.Core
{
    public class LoginManager:DocManager<LoginModel>
    {
        LoginFetcher fetcher;
        LoginUpdater updater;
        UserFetcher userFetcher;
        RoleUserManager roleUserManager;
        public LoginManager() : base()
        {
            userFetcher = new UserFetcher();
            fetcher = new LoginFetcher();
            if (updater == null)
                InjectionUpdater();
            roleUserManager = new RoleUserManager();
        }
        public AsmObject<bool> Register(LoginModel loginModel,int domain,int role)
        {
            string message;
            if (loginModel == null)
            {
                DBHelper.Commit(false);
                LogHelper.Err(this.GetType().Name,String.Format("REGISTER：传入参数为空"));
                return new AsmObject<bool>() { Data = false, Message = "对象不能为空", Result = AmsCode.ArgNotAccept };
            }
            if (loginModel.AutoId > 0)
            {
                DBHelper.Commit( false);
                LogHelper.Err(this.GetType().Name, String.Format("REGISTER：LOGINMODEL的AUTOID不为初始值"));
                return new AsmObject<bool>() { Data = false, Message = "系统内部异常", Result = AmsCode.ArgNotAccept };
            }
            if(fetcher.GetByUserId(loginModel.UserId)!=null)
            {
                DBHelper.Commit( false);
                LogHelper.Err(this.GetType().Name,String.Format("REGISTER:用户 user={0} 的登录档案已经存在", loginModel.UserId));
                return new AsmObject<bool>() { Data = false, Message = String.Format("用户[{0}]已注册",loginModel.UserId), Result = AmsCode.ArgNotAccept };
            }
            loginModel.Password = Util.ToSHA1(loginModel.Password);
            loginModel.LastChanged = Util.Today();
            int effect= updater.Save(loginModel,out message);
            AsmObject<bool> result = null;
            if (effect > 0)
            {
                RoleUserModel roleUserModel = new RoleUserModel() { User = loginModel.UserId, Domain = domain,Role=role };
                var setRoleResult = roleUserManager.Set(roleUserModel);
                if (setRoleResult.Result == AmsCode.Succ)
                {
                    LogHelper.Log(this.GetType().Name, String.Format("REGISTER:创建登录信息 user={0} 成功", loginModel.UserId));
                    result = new AsmObject<bool>() { Data = true, Message = "操作成功", Result = AmsCode.Succ };
                }
                else
                {
                    LogHelper.Err(this.GetType().Name, String.Format("Register:创建用户登录档案user={0} 失败:{1}", loginModel.UserId, message));
                    result = new AsmObject<bool>() { Data = false, Message = message, Result = AmsCode.InnError };
                }
            }
            else
            {
                LogHelper.Err(this.GetType().Name, String.Format("Register:创建用户登录档案user={0} 失败:{1}", loginModel.UserId, message));
                result = new AsmObject<bool>() { Data = false, Message = message, Result = AmsCode.InnError };
            }
            return result;
        }
        public AsmObject<bool> ChangePassword(int userId,string password)
        {
            string message;
            LoginModel loginModel = fetcher.GetByUserId(userId);
            if (loginModel == null)
            {
                LogHelper.Err(this.GetType().Name, String.Format("CHANGEPASSWORD:用户的登录档案 user={0} 不存在", userId));
                return new AsmObject<bool>() { Data = false, Message = String.Format("用户[{0}]未注册", userId), Result = AmsCode.InnError };
            }
            loginModel.LastPassword = loginModel.Password;
            loginModel.Password = Util.ToSHA1(password);
            loginModel.LastChanged = Util.Now();
            int effect = updater.Save(loginModel, out message);
            AsmObject<bool> result = null;
            if (effect > 0)
            {
                LogHelper.Log(this.GetType().Name, String.Format("CHANGEPASSWORD:更新用户密码 user={0} 成功:{1}", loginModel.UserId, message));
                result = new AsmObject<bool>() { Data = true, Message = "操作成功", Result = AmsCode.Succ };
            }
            else
            {
                DBHelper.Commit( false);
                LogHelper.Err(this.GetType().Name, String.Format("CHANGEPASSWORD:更新用户密码 user={0} 失败:{1}", loginModel.UserId, message));
                result = new AsmObject<bool>() { Data = false, Message = message, Result = AmsCode.InnError };
            }
            return result;
        }
        public AsmObject<bool> Lock(int userId, int status)
        {
            string message;
            LoginModel loginModel = fetcher.GetByUserId(userId);
            if (loginModel == null)
            {
                DBHelper.Commit( false);
                LogHelper.Err(this.GetType().Name, String.Format("LOCK:锁定/解锁用户 user={0} 不存在", loginModel.UserId));
                return new AsmObject<bool>() { Data = false, Message = String.Format("用户[{0}]未注册", userId), Result = AmsCode.InnError };
            }
            loginModel.Status = status==0?0:1;
            int effect = updater.Save(loginModel, out message);
            AsmObject<bool> result = null;
            if (effect > 0)
            {
                LogHelper.Log(this.GetType().Name, String.Format("LOCK:锁定/解锁用户 user={0} 成功:{1}", loginModel.UserId, message));
                result = new AsmObject<bool>() { Data = true, Message = "操作成功", Result = AmsCode.Succ };
            }
            else
            {
                DBHelper.Commit( false);
                LogHelper.Err(this.GetType().Name, String.Format("LOCK:锁定/解锁用户 user={0} 失败:{1}", loginModel.UserId, message));
                result = new AsmObject<bool>() { Data = false, Message = message, Result = AmsCode.InnError };
            }
            return result;
        }
        public void UpdateLastLogin(string code)
        {
            LoginUpdaterCreator loginUpdaterCreator = new LoginUpdaterCreator();
            updater = loginUpdaterCreator.CreateLoginUpdaterInstance();
            UserModel userModel = userFetcher.GetByCode(code);
            if(userModel==null)
            {
                LogHelper.Err(this.GetType().Name, String.Format("UPDATELASTLOGIN：无法更新最近登录日期，用户编号 {0} 不存在", code));
                return;
            }
            LoginModel loginModel = fetcher.GetByUserId(userModel.AutoId);
            if (loginModel != null)
            {
                loginModel.LastLogin = Util.Now();
                string message;
                int result = updater.Save(loginModel, out message);
                if(result==0)
                {
                    LogHelper.Err(this.GetType().Name, String.Format("UPDATELASTLOGIN：无法更新最近登录日期，用户编号 {0}:{1}", code, message));
                }
                else
                {
                    LogHelper.Log(this.GetType().Name, String.Format("UPDATELASTLOGIN：更新最近登录日期成功，用户编号 {0}", code));
                }
            }
            else
            {
                LogHelper.Err(this.GetType().Name, String.Format("UPDATELASTLOGIN：无法更新最近登录日期，用户编号 {0} 的登录信息不存在", code));
            }
        }

        protected override BaseUpdater<LoginModel> InjectionUpdater()
        {
            LoginUpdaterCreator loginUpdaterCreator = new LoginUpdaterCreator();
            updater = loginUpdaterCreator.CreateLoginUpdaterInstance();
            return updater;
        }
    }
}
